package cn.conac.rc.ofs.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.conac.rc.ofs.contsant.Contsants;
import cn.conac.rc.ofs.entity.AppFilesEntity;
import cn.conac.rc.ofs.entity.ApprovalEntity;
import cn.conac.rc.ofs.entity.DepartmentEntity;
import cn.conac.rc.ofs.entity.DutyEntity;
import cn.conac.rc.ofs.entity.OrgCombinEntity;
import cn.conac.rc.ofs.entity.OrgEmpEntity;
import cn.conac.rc.ofs.entity.OrgOpinionsEntity;
import cn.conac.rc.ofs.entity.OrgOthersEntity;
import cn.conac.rc.ofs.entity.OrgStatusEntity;
import cn.conac.rc.ofs.entity.OrganizationBaseEntity;
import cn.conac.rc.ofs.entity.OrganizationEntity;
import cn.conac.rc.ofs.entity.VHistApprovalEntity;
import cn.conac.rc.ofs.repository.AppFilesRepository;
import cn.conac.rc.ofs.repository.ApprovalRepository;
import cn.conac.rc.ofs.repository.DepartmentRepository;
import cn.conac.rc.ofs.repository.DutyRepository;
import cn.conac.rc.ofs.repository.OrgCombinRepository;
import cn.conac.rc.ofs.repository.OrgEmpRepository;
import cn.conac.rc.ofs.repository.OrgOpinionsRepository;
import cn.conac.rc.ofs.repository.OrgOthersRepository;
import cn.conac.rc.ofs.repository.OrgStatusRepository;
import cn.conac.rc.ofs.repository.OrganizationBaseRepository;
import cn.conac.rc.ofs.repository.OrganizationRepository;
import cn.conac.rc.ofs.repository.RcOrgEncodeRecordRepository;
import cn.conac.rc.ofs.repository.VHistApprovalRepository;
import cn.conac.rc.ofs.vo.OrgChangeVo;
import cn.conac.rc.ofs.vo.OrgRevVo;

@Service
@Transactional
public class OrgCommonService {

	@Autowired
	OrganizationBaseService orgBaseService;

	@Autowired
	AppFilesService appFilesService;
	
	@Autowired
	ApprovalService appService;

	@Autowired
	DepartmentService departService;
	
	@Autowired
	DutyService dutyService;
	
	@Autowired
	OrgEmpService orgEmpService;
	
	@Autowired
	OrgOthersService orgOthersService;
	
	@Autowired
	OrgStatusService orgStatusService;
	
	@Autowired
	OrgCombinService orgCombinService;
	
	@Autowired
	OrganizationService  organizationService;
	
//	@Autowired
//	CodeService  codeService;
	
	@Autowired
	OrgOpinionsService orgOpinionsService;
	
	//*****************分割线************************
	@Autowired
	OrganizationRepository orgRepository;
	
	@Autowired
	OrgOthersRepository orgOthersRepository;
	
	@Autowired
	DepartmentRepository departmentRepository;
	
	@Autowired
	DutyRepository dutyRepository;
	
	@Autowired
	AppFilesRepository appFilesRepository;
	
	@Autowired
	ApprovalRepository appRepository;
	
	@Autowired
	OrganizationBaseRepository orgBaseRepository;
	
	@Autowired
	OrgStatusRepository orgStatusRepository;
	
	@Autowired
	OrgOpinionsRepository orgOpinionsRepository;
	
	@Autowired
	OrgEmpRepository orgEmpRepository;
	
	@Autowired
	OrgCombinRepository orgCombinRepository;
	
	@Autowired
	RcOrgEncodeRecordRepository rcOrgEncodeRecordRepository;
	
	@Autowired
	VHistApprovalRepository  vHistApprovalRepository;
	
	/**
	 * 三定信息变更(各表信息复制)
	 * @param oldOrgId
	 * @return newBaseId
	 */
	public Integer orgsCopy(Integer orgId, String updateType) {
		
		Integer oldBaseId = null;
		// 1.获取部门相关基本信息(包括BaseId)
		OrganizationBaseEntity oldOrgBase = orgBaseService.findByOrgId(orgId);
		if(null != oldOrgBase) {
			oldBaseId = oldOrgBase.getId();
		} else {
			return null;
		}

		// 2.copy部门相关的各项信息
		// 2.1 基本信息的copy
		OrganizationBaseEntity newOrgBase = orgBaseService.copyOrgBaseInfo(orgId);
		Integer newBaseId = newOrgBase.getId();
		
		if( null != updateType && "40".equals(updateType)) {
			// 2.2 批文信息的copy
			appService.copyApprovalInfo(oldBaseId, newBaseId);
			// 2.3 批文文件信息的copy
			appFilesService.copyAppFilesInfo(oldBaseId, newBaseId);
		} else if (null  != updateType) {
			ApprovalEntity approvalEntity = new ApprovalEntity();
			approvalEntity.setId(newBaseId);
			appService.save(approvalEntity);
		}
		// 2.4 职能职责的copy
		List<DutyEntity> dutyList = dutyService.copyDutyListWithOrgId(oldBaseId, newBaseId);
		// 2.5 内设部门的copy
		departService.copyDepartmentInfo(oldBaseId, newBaseId, dutyList);
		// 2.6 编制信息的copy
		orgEmpService.copyOrgEmpInfo(oldBaseId, newBaseId);
		// 2.7 其他信息的copy
		orgOthersService.copyOrgOthersInfo(oldBaseId, newBaseId);
		
		return newBaseId;
	}
	
	
	/**
	 * 对已撤并部门的撤并各表信息复制
	 * @param oldOrgId
	 * @return newBaseId
	 */
	public Integer orgsHistCopy(Integer orgId, String updateType) {
		
		// 1.获取部门相关基本信息(包括BaseId)
		List<VHistApprovalEntity>   vHistApprovalEntityList =
				vHistApprovalRepository.findByOrgIdOrderByAppDateDescIsHistoryAscUpdateTimeDesc(orgId.toString());
		Integer oldBaseId = null;
		if(null != vHistApprovalEntityList && vHistApprovalEntityList.size() > 0 ) {
			// 补录撤并部门场合找到最近的一条记录的baseId
			oldBaseId = vHistApprovalEntityList.get(0).getId();
		}  else {
			return null;
		}
		
		// 2.copy部门相关的各项信息
		// 2.1 基本信息的copy
		OrganizationBaseEntity newOrgBase = orgBaseService.copyOrgBaseInfoByBaseId(oldBaseId);
		Integer newBaseId = newOrgBase.getId();
		
		if( null != updateType && "40".equals(updateType)) {
			// 2.2 批文信息的copy
			appService.copyApprovalInfo(oldBaseId, newBaseId);
			// 2.3 批文文件信息的copy
			appFilesService.copyAppFilesInfo(oldBaseId, newBaseId);
		} else if (null  != updateType) {
			ApprovalEntity approvalEntity = new ApprovalEntity();
			approvalEntity.setId(newBaseId);
			appService.save(approvalEntity);
		}
		// 2.4 职能职责的copy
		List<DutyEntity> dutyList = dutyService.copyDutyListWithOrgId(oldBaseId, newBaseId);
		// 2.5 内设部门的copy
		departService.copyDepartmentInfo(oldBaseId, newBaseId, dutyList);
		// 2.6 编制信息的copy
		orgEmpService.copyOrgEmpInfo(oldBaseId, newBaseId);
		// 2.7 其他信息的copy
		orgOthersService.copyOrgOthersInfo(oldBaseId, newBaseId);
		
		return newBaseId;
	}
	
	/**
	 * 三定信息变更(各表信息复制)
	 * @param oldOrgId
	 * @return newBaseId
	 */
	public Integer orgsCopyByBaseId(Integer oldBaseId, String updateType) {

		// 2.copy部门相关的各项信息
		// 2.1 基本信息的copy
		OrganizationBaseEntity newOrgBase = orgBaseService.copyOrgBaseInfoByBaseId(oldBaseId);
		Integer newBaseId = newOrgBase.getId();
		
		if( null != updateType && "40".equals(updateType)) {
			// 2.2 批文信息的copy
			appService.copyApprovalInfo(oldBaseId, newBaseId);
			// 2.3 批文文件信息的copy
			appFilesService.copyAppFilesInfo(oldBaseId, newBaseId);
		} else if (null  != updateType) {
			ApprovalEntity approvalEntity = new ApprovalEntity();
			approvalEntity.setId(newBaseId);
			appService.save(approvalEntity);
		}
		// 2.4 职能职责的copy
		List<DutyEntity> dutyList = dutyService.copyDutyListWithOrgId(oldBaseId, newBaseId);
		// 2.5 内设部门的copy
		departService.copyDepartmentInfo(oldBaseId, newBaseId, dutyList);
		// 2.6 编制信息的copy
		orgEmpService.copyOrgEmpInfo(oldBaseId, newBaseId);
		// 2.7 其他信息的copy
		orgOthersService.copyOrgOthersInfo(oldBaseId, newBaseId);
		
		return newBaseId;
	}
	
	/**
	 * 三定信息的base表创建
	 * @param orgId
	 */
	public Integer orgsCreateBaseInfo(Integer orgId) {
		
		// Base表信息设置
		OrganizationBaseEntity baseEntity = new OrganizationBaseEntity();
		baseEntity.setOrgId(orgId);

		// 根据部门库的值设置初始值
		OrganizationEntity  organizationEntity = organizationService.findById(orgId);
		// 部门名称是必须的
		baseEntity.setName(organizationEntity.getName());
		baseEntity.setType(organizationEntity.getType());
		baseEntity.setIsComp(organizationEntity.getIsComp());
		baseEntity.setCompId(organizationEntity.getParentId());
		baseEntity.setOwnSys(organizationEntity.getOwnSys());
		baseEntity.setIsSecret(organizationEntity.getIsSecret());
		// 保存新Base信息并返回
		OrganizationBaseEntity newOrgBase = orgBaseRepository.save(baseEntity);
			
		return newOrgBase.getId();
	}

	/**
	 * 三定信息变更(六大步相关表及部门状态信息表复制)
	 * @param orgChangeVo
	 */
	public Integer orgChange(OrgChangeVo orgChangeVo) {
		
		Integer newBaseId = null;
		// 部门管理变更场合
		if(Contsants.ORG_CHANGE_MODEL_CURR.equals(orgChangeVo.getOperationStatusVo().getOperation())) {
			newBaseId = orgsCopy(orgChangeVo.getOperationStatusVo().getOrgId(), orgChangeVo.getOrgStatusEntity().getStatus());
			// 2.8 保存机构基本状态表
			orgChangeVo.getOrgStatusEntity().setId(newBaseId);
			orgChangeVo.getOrgStatusEntity().setUpdateTime(new Date());
			orgStatusService.save(orgChangeVo.getOrgStatusEntity());
		} else if (Contsants.ORG_CHANGE_MODEL_INPUT.equals(orgChangeVo.getOperationStatusVo().getOperation())){
			// 历史沿革直接录入场合
			newBaseId = orgsCreateBaseInfo(orgChangeVo.getOperationStatusVo().getOrgId());
			// 2.8 保存机构基本状态表
			orgChangeVo.getOrgStatusEntity().setId(newBaseId);
			orgChangeVo.getOrgStatusEntity().setUpdateTime(new Date());
			orgStatusService.save(orgChangeVo.getOrgStatusEntity());
		} else {
			// 历史沿革复制场合(默认场合)
			newBaseId = orgsCopyByBaseId(orgChangeVo.getOperationStatusVo().getBaseId(), orgChangeVo.getOrgStatusEntity().getStatus());
			// 2.8 保存机构基本状态表
			orgChangeVo.getOrgStatusEntity().setId(newBaseId);
			orgChangeVo.getOrgStatusEntity().setUpdateTime(new Date());
			orgStatusService.save(orgChangeVo.getOrgStatusEntity());
		}
		return newBaseId;
	}
	
	
	/**
	 * 三定信息撤并的保存
	 * @param oldOrgId
	 * 	@param isBianBan
	 * @param orgRevVo
	 */
	public String orgRevSave(Integer orgId, String bianBanFlag, OrgRevVo orgRevVo) {
		
		 int orgSaveFlag = 0;
		 Integer newBaseId = null;
		//  部门信息复制
		OrganizationEntity organizationEntity = organizationService.findById(orgId);
		if(Contsants.OFS_ORGANIZATION_FLAG_CANCEL.equals(organizationEntity.getStatus())) {
			// 补录撤并部门场合（部门库本身是撤并状态）
			newBaseId = orgsHistCopy(orgId, null);
		} else {
			newBaseId = orgsCopy(orgId, null);
		}
		if(null == newBaseId) {
			return null;
		}
		String retStr = newBaseId.toString() + ",";
		
		// 状态信息更新
		OrgStatusEntity orgStatusEntity = orgRevVo.getOrgStatusEntity();
		orgStatusEntity.setId(newBaseId);
		orgStatusEntity.setUpdateTime(new Date());
		if("1".equals(bianBanFlag)) {
			// 编办场合 设置为审核通过
			orgStatusEntity.setStatus(Contsants.OFS_AUDIT_THROUGH);
			if(Contsants.OFS_ORG_STATUS_IS_HISTORY_FALSE.toString().equals(orgStatusEntity.getIsHistory())) {
				orgSaveFlag = 1;
			} 
		} else {
			//委办局场合
			if(Contsants.OFS_ORG_STATUS_IS_HISTORY_TRUE.toString().equals(orgStatusEntity.getIsHistory())) {
				// 历史沿革场合 设置为审核通过
				orgStatusEntity.setStatus(Contsants.OFS_AUDIT_THROUGH);
			} else {
				// 非历史沿革场合（部门管理） 设置为待审核
				orgStatusEntity.setStatus(Contsants.OFS_STATUS_PRE_AUDIT);
			}
		}
		orgStatusService.save(orgStatusEntity);
		
		// 批文信息更新
		ApprovalEntity approvalEntity = orgRevVo.getApprovalEntity();
		approvalEntity.setId(newBaseId);
		appService.save(approvalEntity);
		
		// 批文文件信息更新
		AppFilesEntity appFilesEntity = orgRevVo.getAppFilesEntity();
		appFilesEntity.setBaseId(newBaseId);
		appFilesService.save(appFilesEntity);
		
		// 部门合并信息保存
		List<OrgCombinEntity>  orgCombinList = orgRevVo.getOrgCombinList();
		for(OrgCombinEntity ogCombinEntity:  orgCombinList) {
			ogCombinEntity.setBaseId(newBaseId);
			orgCombinService.save(ogCombinEntity);
		}
		if(orgSaveFlag == 1) {
			// 编办场合同步更新部门库信息
			//OrganizationEntity  organizationEntity = organizationService.findById(orgId);
			organizationEntity.setBaseId(newBaseId);
			organizationEntity.setStatus(Contsants.OFS_ORGANIZATION_FLAG_CANCEL);
			// 更新部门库信息表
			organizationService.save(organizationEntity);
			// 保存审核意见表
			OrgOpinionsEntity orgOpinionsEntity = new OrgOpinionsEntity();
			orgOpinionsEntity.setBaseId(newBaseId);
			orgOpinionsEntity.setAuditTime(new Date());
			orgOpinionsService.save(orgOpinionsEntity);
			// 顶级主管部门场合，删除部门编码表中的信息
//			String findId = null;
//			
//			if(null == organizationEntity.getParentId()  &&
//					 Contsants.OFS_ORG_STR_IS_COMP.equals(organizationEntity.getIsComp()) ) {
//				// 是顶级主管部门场合，删除部门编码表中的信息，以确保主管部门的后四位为"0000"
//				if(null != organizationEntity.getCode()) {
//					findId = organizationEntity.getCode().substring(0, 9);
//				}
//				if(null != findId) {
//					RcOrgEncodeRecordEntity rcOrgEncodeRecordEntity  = rcOrgEncodeRecordRepository.findByFindId(findId);
//					if(null != rcOrgEncodeRecordEntity) {
//						rcOrgEncodeRecordRepository.deleteByFindId(findId);
//					}
//					retStr += findId;
//				}
//			}
		}
		
		return retStr;
	}
	
	/**
	 * 三定信息撤并的更新
	 * @param baseId
	 * @param orgRevVo
	 */
	public Integer orgRevUpdate(Integer baseId, OrgRevVo orgRevVo) {
		
		// 状态信息更新
		OrgStatusEntity orgStatusEntity = orgRevVo.getOrgStatusEntity();
		// 设置ID
		orgStatusEntity.setId(baseId);
		OrgStatusEntity orgStatusEntityDb = orgStatusService.findById(baseId);
		if(null != orgStatusEntityDb) {
			// 更新用户ID
			if(null != orgStatusEntityDb.getRegUserId()) {
				orgStatusEntity.setRegUserId(orgStatusEntityDb.getRegUserId());
			}
			if(null != orgStatusEntityDb.getCreateTime()) {
				orgStatusEntity.setCreateTime(orgStatusEntityDb.getCreateTime());
			}
		} 
		orgStatusEntity.setUpdateTime(new Date());
		orgStatusService.save(orgStatusEntity);
		
		
		// 批文信息更新
		ApprovalEntity approvalEntity = orgRevVo.getApprovalEntity();
		approvalEntity.setId(baseId);
		appService.save(approvalEntity);

		// 批文文件信息更新
		AppFilesEntity appFilesEntity = orgRevVo.getAppFilesEntity();
		List<AppFilesEntity> appFilesList  = appFilesRepository.findByBaseId(baseId);
		if(null != appFilesList) {
			appFilesEntity.setId(appFilesList.get(0).getId());
		}
		appFilesEntity.setBaseId(baseId);
		appFilesService.save(appFilesEntity);
		
		 // 记录原来部门合并信息
		Map<Integer,Integer> oldOrgIdIdMap =new HashMap<Integer,Integer>();
		 List<OrgCombinEntity> orgCombinList = orgCombinRepository.findByBaseId(baseId);
		 if(null != orgCombinList) {
			 for(OrgCombinEntity ogCombinEntity:  orgCombinList) {
				 oldOrgIdIdMap.put(ogCombinEntity.getOrgId(), ogCombinEntity.getId());
			 }
		 }
			 
		// 部门合并信息保存
		List<OrgCombinEntity>  newOrgCombinList = orgRevVo.getOrgCombinList();
		for(OrgCombinEntity ogCombinEntity:  newOrgCombinList) {
			if(oldOrgIdIdMap.containsKey(ogCombinEntity.getOrgId())) {
				ogCombinEntity.setId(oldOrgIdIdMap.get(ogCombinEntity.getOrgId()));
				oldOrgIdIdMap.remove(ogCombinEntity.getOrgId());
			} 
			ogCombinEntity.setBaseId(baseId);
			orgCombinService.save(ogCombinEntity);
		}
		
		// 删除在更新前的不是本次选中的合并部门的信息
		if(oldOrgIdIdMap.size() > 0) {
			for(Integer combinId : oldOrgIdIdMap.values()){
				orgCombinRepository.delete(combinId);
			}
		}
		
		return baseId;
	}
	
	
	/**
	 * 根据部门ID和部门baseID删除审核通过部门相关信息
	 * 
	 * @param orgId
	 * @param baseId
	 * @return void
	 */
	public String deleteOrgs(Integer orgId, List<Integer>  baseIdsList ) {
	
		List<OrgOpinionsEntity>  orgOpinionsList = null;
//		String findId =null;
		String parentId =null;
		
		List<OrganizationBaseEntity>  baseInfoList =  orgBaseService.findListByOrgId(orgId);
		for (OrganizationBaseEntity baseEntity : baseInfoList){
			// 删除审批信息表
			orgOpinionsList = orgOpinionsRepository.findByBaseId(baseEntity.getId());
			if(null !=orgOpinionsList){
				orgOpinionsRepository.deleteByBaseId(baseEntity.getId());
			}
			// 删除六步相关的数据和部门状态信息
			deletePreReleaseOrgs(baseEntity.getId());
			baseIdsList.add(baseEntity.getId());
		}
		
//		OrganizationEntity  organizationEntity = organizationService.findById(orgId);
//		if(null == organizationEntity.getParentId()  &&
//				 Contsants.OFS_ORG_STR_IS_COMP.equals(organizationEntity.getIsComp()) ){
//			// 是顶级主管部门场合，删除部门编码表中的信息，以确保主管部门的后四位为"0000"
//			if(null != organizationEntity.getCode()) {
//				findId = organizationEntity.getCode().substring(0, 9);
//			}
//			if(null != findId) {
//				RcOrgEncodeRecordEntity rcOrgEncodeRecordEntity  = rcOrgEncodeRecordRepository.findByFindId(findId);
//				if(null != rcOrgEncodeRecordEntity) {
//					rcOrgEncodeRecordRepository.deleteByFindId(findId);
//				}
//				//codeService.deleteByFindId(findId);
//			}
//		}
		OrganizationEntity  organizationEntity = organizationService.findById(orgId);
		if(null != organizationEntity) {
			if(null != organizationEntity.getParentId()){
				parentId = organizationEntity.getParentId().toString();
			}
			// 删除部门库信息表
			orgRepository.delete(orgId);
		}		
		return  parentId;
	}
	
	/**
	 * 根据部门ID删除部门库相关信息（如果为顶级主管部门场合同时删除编码信息）
	 * 
	 * @param orgId
	 * @param baseId
	 * @return void
	 */
	public String deleteOrganizationInfo(Integer orgId) {
		
		// 删除部门库信息表
//		String findId = null;
		String parentId = null;
		OrganizationEntity  organizationEntity = organizationService.findById(orgId);
		if(null != organizationEntity) {
//			if(null == organizationEntity.getParentId()  &&
//					 Contsants.OFS_ORG_STR_IS_COMP.equals(organizationEntity.getIsComp()) ){
//				// 是顶级主管部门场合，删除部门编码表中的信息，以确保主管部门的后四位为"0000"
//				if(null != organizationEntity.getCode()) {
//					findId = organizationEntity.getCode().substring(0, 9);
//				}
//				if(null != findId) {
//					RcOrgEncodeRecordEntity rcOrgEncodeRecordEntity  = rcOrgEncodeRecordRepository.findByFindId(findId);
//					if(null != rcOrgEncodeRecordEntity) {
//						rcOrgEncodeRecordRepository.deleteByFindId(findId);
//					}
//					//codeService.deleteByFindId(findId);
//				}
//			}
			
			if(null != organizationEntity.getParentId()){
				parentId = organizationEntity.getParentId().toString();
			}
			// 删除部门库信息表
			orgRepository.delete(orgId);
				
		}
		return  parentId;
	}
	
	/**
	 * 根据部门ID和部门baseID删除审核通过部门相关信息
	 * 
	 * @param orgId
	 * @return List<Integer> baseIds
	 */
	public List<Integer> deleteAuditedOrgs(Integer orgId) {
		
		List<Integer> baseIdsList = new ArrayList<Integer>();
		List<OrgOpinionsEntity>  orgOpinionsList = null;
		List<OrganizationBaseEntity>  baseInfoList =  orgBaseService.findListByOrgId(orgId);
		for (OrganizationBaseEntity baseEntity : baseInfoList){
			// 删除审批信息表
			orgOpinionsList = orgOpinionsRepository.findByBaseId(baseEntity.getId());
			if(null !=orgOpinionsList){
				orgOpinionsRepository.deleteByBaseId(baseEntity.getId());
			}
			// 删除六步相关的数据和部门状态信息
			deletePreReleaseOrgs(baseEntity.getId());
			baseIdsList.add(baseEntity.getId());
		}
		// 更新部门库表的baseId为null
		OrganizationEntity  organizationEntity = organizationService.findById(orgId);
		organizationEntity.setBaseId(null);
		organizationService.save(organizationEntity);
		return baseIdsList;
	}
	
	/**
	 * 根据部门ID和部门baseID删除审核通过部门相关信息
	 * 
	 * @param baseId
	 * @return 下一个历史节点的baseId
	 */
	public Integer deleteHistNodeOrg(Integer baseId) {
		List<OrgOpinionsEntity>  orgOpinionsList = null;
		Integer nextNodeBaseId = null;
		OrganizationEntity  organizationEntity = orgRepository.findByBaseId(baseId);
		if(null != organizationEntity) {
			// 删除节点为最新节点场合
			List<VHistApprovalEntity>  vHistApprovaList =  
					vHistApprovalRepository.findByOrgIdOrderByAppDateDescIsHistoryAscUpdateTimeDesc(organizationEntity.getId().toString());
			if(vHistApprovaList.size() > 1) {
				// 历史节点有多个的场合
				// 更新部门库表的baseId为下一个节点的baseId
				nextNodeBaseId = vHistApprovaList.get(1).getId();
				organizationEntity.setBaseId(nextNodeBaseId);
			} else {
				// 历史节点只有一个的场合
				// 更新部门库表的baseId为null
				organizationEntity.setBaseId(null);
			}
			organizationService.save(organizationEntity);
		} 
		
		// 删除审批信息表
		orgOpinionsList = orgOpinionsRepository.findByBaseId(baseId);
		if(null !=orgOpinionsList){
			orgOpinionsRepository.deleteByBaseId(baseId);
		}
		// 删除六步相关的数据和部门状态信息
		deletePreReleaseOrgs(baseId);
		return nextNodeBaseId;
	}
	
	/**
	 * 根据部门baseID删除未提交的部门相关信息
	 * 
	 * @param baseId
	 * @return void
	 */
	public void deletePreReleaseOrgs(Integer baseId) {
		
		// 删除其他和附则信息表
		OrgOthersEntity orgOthersEntity = orgOthersService.findById(baseId);
		if(null != orgOthersEntity){
			orgOthersRepository.delete(baseId);
		}
		
		// 删除编制信息表
		OrgEmpEntity  orgEmpEntity = orgEmpService.findById(baseId);
		if(null != orgEmpEntity) {
			orgEmpRepository.delete(baseId);
		}
		
		// 删除内设机构信息表
		 List<DepartmentEntity> deptList =  departService.findByBaseId(baseId);
		 if(null != deptList) {
			 departmentRepository.deleteByBaseId(baseId);
		 }
		
		// 删除职能职责信息表
		 List<DutyEntity> dutyList = dutyService.findByBaseId(baseId);
		 if(null != dutyList){
			 dutyRepository.deleteByBaseId(baseId);
		 }
		
		// 删除批文文件表信息表
		 List<AppFilesEntity> appFilesList  = appFilesRepository.findByBaseId(baseId);
		 if(null != appFilesList) {
			 appFilesRepository.deleteByBaseId(baseId);
		 }
		
		// 删除部门合并信息表
		 List<OrgCombinEntity> orgCombinList = orgCombinRepository.findByBaseId(baseId);
		 if(null != orgCombinList) {
			 orgCombinRepository.deleteByBaseId(baseId);
		 }
		
		// 删除批文表信息表
	    ApprovalEntity approvalEntity = appService.findById(baseId);
	    if(null != approvalEntity){
	    	appRepository.delete(baseId);
	    }
		
		// 删除部门状态信息表
	    OrgStatusEntity orgStatusEntity = orgStatusService.findById(baseId);
	    if(null != orgStatusEntity) {
	    	orgStatusRepository.delete(baseId);
	    }
		
		// 删除部门基本信息表信息表 
	    OrganizationBaseEntity orgBaseEntity = orgBaseService.findById(baseId);
	    if(null != orgBaseEntity) {
	    	orgBaseRepository.delete(baseId);
	    }
	}

	/**
	 * 三定变更或部门撤并的校验逻辑
	 * @param orgId 部门orgId
	 * @return String check结果
	 */
	public String ofsChangeOrRevCheck(Integer orgId){
		// 返回结果字段
		String returnFlg = "true";
		List<OrganizationBaseEntity> baseOrgList = orgBaseRepository.findOrgListByOrgId4Check(orgId);
        // 如果存在状态为【待提交】【待审核】【驳回】的数据，则返回false
		if(baseOrgList != null && baseOrgList.size() > 0){
            returnFlg = "false";
		} else {
            // 通过OrgId获取对应的Base信息
            OrganizationBaseEntity baseEntity = orgBaseRepository.findByOrgId(orgId);
            // 同时获取对应此机构的子机构信息
            List<OrganizationBaseEntity> childBaseOrgList = orgBaseRepository.findChildOrgListByOrgId(orgId);
            // 如果此机构为主管机构并且存在子机构
            if(childBaseOrgList != null && childBaseOrgList.size() > 0 && "1".equals(baseEntity.getIsComp())){
                Integer childBasicOrgId = null;
                Integer childMainOrgId = null;
                OrganizationBaseEntity childBaseOrg = null;
                OrgStatusEntity orgStatusEntity = null;
                // 判断子机构是否存在有【撤并变更】状态的
                for(OrganizationBaseEntity orgBaseEntity : childBaseOrgList){
                    childBasicOrgId = orgBaseEntity.getId();
                    childMainOrgId = orgBaseEntity.getOrgId();
                    childBaseOrg = orgBaseRepository.findByOrgId(childMainOrgId);
                    orgStatusEntity = orgStatusRepository.findOne(childBasicOrgId);
                    if(null != childBaseOrg && null != orgStatusEntity &&
                            childBasicOrgId.equals(childBaseOrg.getId()) && !"50".equals(orgStatusEntity.getUpdateType())){
                        returnFlg = "false_childOrgs";
                        break;
                    }
                }
            }
        }
        return returnFlg;
	}

}
